<%@ page import="com.alibaba.fastjson.JSON" %>
<%@ page pageEncoding="UTF-8"%>
<%@ include file="/common/common.jsp"%>
<%@ include file="/common/catch.jsp"%>
<%!
	static  String TOKEN = "36fda170983b49408f5d111490b8e2e0";
	
	public static String InitToken() {
		Map map = new HashMap();
		map.put("loginName", "15370017289");
		map.put("password", Tools.getMD5("123456"));
		String json = HttpUtil.post("http://api.ifuifu.com/api/doctor/op/login", map);
		TOKEN = (String)JSONUtil.fromJson(json, new TypeReference<Map>(){}).get("token");
		return TOKEN;
	}
	
	public static String getSubItem(String id) {
		Map param = new HashMap();
		param.put("token", TOKEN);
		param.put("page", "0");
		param.put("specialtyId", id);
		String json = HttpUtil.post("http://api.ifuifu.com/api/doctor/templategroup/list", param);
		return json;
	}
	
	public static String getCases(String id) {
		Map param = new HashMap();
		param.put("token", TOKEN);
		param.put("page", "1");
		param.put("type", "1");
		param.put("tempname", "");
		param.put("templateGroupId", id);
		String json = HttpUtil.post("http://api.ifuifu.com/api/doctor/template/commonlist", param);
		return json;
	}
	
	public static String showCase(String id) {
		Map param = new HashMap();
		param.put("token", TOKEN);
		String json = HttpUtil.post("http://api.ifuifu.com/api/doctor/template/" + id, param);
		return json;
	}
	
	public static String showSurvey(String id) {
		return HttpUtil.get("http://api.ifuifu.com/wxapi/wx/getSurveyDetail?surveyId=" + id);
	}
	
	// 抓取远程图片到本地服务器，并返回本地服务器地址集合
	public String imgsCompare(Element content, String domian) {
		Elements imgs = content.select("img");
		List<HashMap<String, String>> imgsJson = new ArrayList<HashMap<String, String>>();
		int size = imgs.size();
		for(int i = 0; i < size; i++) {
			String src = imgs.get(i).attr("src").toString();
			String domianIgnore = domian.replace("www.","");
			if((!src.startsWith(domian)) && (!src.startsWith(domianIgnore))) {
				src = domian + src;
			}
			String big = "";
			String pixel  = "550 * 366";
			try {
				 big = ImageUtil.big(src);
			} catch (Exception e) {
				
			}
			
			String sizeJson = ImageUtil.size(big);
			 pixel  = "550 * 366";
			List<HashMap<String, String>> sizeList = JSONUtil.fromJson(sizeJson, new TypeReference<List<HashMap<String, String>>>(){});
			if(sizeList.size() > 0) {
				HashMap<String, String> sizeMap = sizeList.get(0);
				pixel = sizeMap.get("width") + " * " + sizeMap.get("height");
			}
			// 存入HashMap中
			HashMap<String, String> map = new HashMap<String, String>();
			map.put("ref","!--IMG#" + i + "--");
			map.put("pixel", pixel);
			map.put("src", big);
			// 循环添加某篇新闻
			imgsJson.add(map);
		}
		return JSONUtil.toJson(imgsJson);
	}
%>
<%!
	public void saveCategory() {
		String[] areas = new String[]{"1", "2", "3", "4"};
		Map<String, String> aMap = new HashMap<String, String>();
		aMap.put("1", "手术专区,手术治疗");
		aMap.put("2", "康复专区,骨科康复治疗");
		aMap.put("3", "护理专区,骨科护理治疗");
		aMap.put("4", "风湿专区,骨科风湿治疗");
		for (String areaId: areas) {
			String json = getSubItem(areaId);
			Map visitCategory = new HashMap();
			visitCategory.put("title", aMap.get(areaId).split(",")[0]);
			visitCategory.put("sub_title", aMap.get(areaId).split(",")[1]);
			visitCategory.put("status", 1);
			visitCategory.put("src_id", areaId);
			visitCategory.put("json", "{}");
			Integer pid = (Integer)DBTools.db("basedb").addItem("visit_category", visitCategory);
			Map map = JSONUtil.fromJson(json, new TypeReference<Map>(){});
			String resCode = Tools.getDesc(map.get("resCode"));
			if (resCode.equals("0000")) {
				List<Map> list = (List<Map>)map.get("resultList");
				for (Map subMap:list) {
					String subId = Tools.getDesc(subMap.get("id")).replaceAll("\\.0", "");
					Map visitSubCategory = new HashMap();
					visitSubCategory.put("title", subMap.get("title")+"");
					visitSubCategory.put("sub_title", subMap.get("subTitle")+"");
					visitSubCategory.put("status", 1);
					visitSubCategory.put("src_id", subId);
					visitSubCategory.put("parent_id", pid);
					visitSubCategory.put("json", JSONUtil.toJson(subMap));
					Integer sid = (Integer)DBTools.db("basedb").addItem("visit_category", visitSubCategory);
					String cases = getCases(subId);
					Map resCases = JSONUtil.fromJson(cases, new TypeReference<Map>(){});
					String resCodeCase = Tools.getDesc(resCases.get("resCode"));
					if (resCodeCase.equals("0000")) {
						List<Map> caseList = (List<Map>)resCases.get("resultList");
						for (Map caseMap:caseList){					
							String caseId = Tools.getDesc(caseMap.get("id")).replaceAll("\\.0", "");
							String caseJson = showCase(caseId);
							Map caseShow = JSONUtil.fromJson(caseJson, new TypeReference<Map>(){});
							String resShowCode = Tools.getDesc(caseShow.get("resCode"));
							Map visitTemp = new HashMap();
							visitTemp.put("template_name", caseMap.get("templateName")+"");
							visitTemp.put("template_type", caseMap.get("templateType")+"");
							visitTemp.put("status", 1);
							visitTemp.put("src_id", caseId);
							visitTemp.put("json", caseJson);
							Integer caseTempid = (Integer)DBTools.db("basedb").addItem("visit_template", visitTemp);
							Map visitlink = new HashMap();
							visitlink.put("cate_id", sid);
							visitlink.put("src_cate_id", subId);
							visitlink.put("case_id", caseTempid);
							visitlink.put("src_case_id", caseId);
							visitlink.put("status", 1);
							visitlink.put("src_id", caseId);
							visitlink.put("json", JSONUtil.toJson(caseMap));
							DBTools.db("basedb").addItem("visit_link", visitlink);
						}
					}
				}
			}
		}
	}
%>
<%!
	public void template() {
		List<Map> list = QBuilder.db("basedb").queryHql("from visit_template");
		for (Map map:list) {
			String json = map.get("json")+"";
			Integer tid = (Integer)map.get("id");
			Map tMap = JSONUtil.fromJson(json, new TypeReference<Map>(){});
			Map model = (Map)tMap.get("model");
			List<Map> templatePointList = (List<Map> )model.get("templatePointList");
			//out.println(GsonUtil.toJson(templatePointList));
			for (Map tempPoint:templatePointList) {
				Map point = new HashMap();
				point.put("title", tempPoint.get("pointName")+"");
				point.put("template_id", tid);
				point.put("status", 1);
				point.put("src_id", Tools.getDesc(tempPoint.get("id")).replaceAll("\\.0" , ""));
				point.put("json", JSONUtil.toJson(tempPoint));
				Integer pid = (Integer)DBTools.db("basedb").addItem("visit_point", point);
				List<Map> pointLinkList = (List<Map> )tempPoint.get("pointLinkList");
				Integer linkOrder = 1;
				for (Map pointMap:pointLinkList) {
					Map pointLink = new HashMap();
					pointLink.put("point_id", pid);
					pointLink.put("status", 1);
					pointLink.put("link_type", Tools.getInt(pointMap.get("linkType")+""));
					pointLink.put("link_order", linkOrder);
					//pointLink.put("link_id", caseId);
					pointLink.put("json", JSONUtil.toJson(pointMap));
					Integer plid = (Integer)DBTools.db("basedb").addItem("visit_point_link", pointLink);
					linkOrder++;
				}
			}		
		}
	}
%>
<%!
	public void detail() {
		List<Map> list = QBuilder.db("basedb").queryHql("from visit_point_link");
		for (Map map:list) {
			String json = map.get("json")+"";
			Integer tid = (Integer)map.get("id");
			Integer linkType = (Integer)map.get("link_type");
			Map tMap = JSONUtil.fromJson(json, new TypeReference<Map>(){});
			String linkIdSrc = 	Tools.getDesc(tMap.get("linkId")).replaceAll("\\.0", "");
			if (linkType == 0) {
				List<Survey>  sList = QBuilder.db("basedb").queryHql("from Survey where json='{\"survey_src_id\":\"" + linkIdSrc + "\"}'");			
				if (sList.size() != 0) {
					Survey exS = sList.get(0);
					map.put("link_id", exS.getId());
					DBTools.db("basedb").modItem("visit_point_link", map);
					continue;
				}
				json = showSurvey(linkIdSrc);
				Map surveyMap = JSONUtil.fromJson(json, new TypeReference<Map>(){});
				if (Tools.getDesc(surveyMap.get("resCode")).equals("0000")) {
					Map surverModel = (Map)surveyMap.get("model");
					String title = surverModel.get("title") + "";
					String titleDesc = surverModel.get("surveyDesc")+"";
					Survey survey = new Survey();
					survey.setTitle(title);
					survey.setDetail(titleDesc);
					survey.setJson("survey_src_id", linkIdSrc);
					Integer sid = (Integer)DBTools.db("basedb").addItem(survey);
					map.put("link_id", sid);
					DBTools.db("basedb").modItem("visit_point_link", map);
					List<Map> questionList = (List<Map>)surverModel.get("questionList");
					int qOrder = 1;
					for (Map questionMap:questionList) {
						String questionTitle = questionMap.get("questionTitle") + "";
						String questionType = questionMap.get("questionType") + "";
						String questionCode = questionMap.get("questionCode") + "";
						SurveyQuestion sq = new SurveyQuestion();
						sq.setSurveyId(sid);
						sq.setTitle(filterIllegalCharacter(questionTitle));
						sq.setShowOrder(qOrder);
						sq.setType(Tools.getInt(questionType));
						qOrder++;
						Integer qid =  (Integer)DBTools.db("basedb").addItem(sq);
						List<Map> optionList = (List<Map>)questionMap.get("optionList");
						int oOrder = 1;
						for (Map optionMap:optionList) {
							SurveyOptions so = new SurveyOptions();
							String optionText = optionMap.get("optionText") + "";
							String optionScore = Tools.getDesc(optionMap.get("optionScore")).replaceAll("\\.0", "");
							String sortBy = Tools.getDesc(optionMap.get("sortBy")).replaceAll("\\.0", "");
							so.setQuestId(qid);
							so.setContent(filterIllegalCharacter(optionText));
							so.setScore(Tools.getInt(optionScore));
							so.setShowOrder(oOrder);
							oOrder++;
							DBTools.db("basedb").addItem(so);
						}
					}
				}
			} 
			if (linkType == 1) {
				List<News>  nList = QBuilder.db("basedb").queryHql("from News where newsId='" + linkIdSrc + "' and hospital=999 and category=0");			
				if (nList.size() != 0) {
					News exS = nList.get(0);
					map.put("link_id", exS.getId());
					DBTools.db("basedb").modItem("visit_point_link", map);
					continue;
				}
				String html = HttpUtil.get("https://ms.ifuifu.com/Index/detail/id/" + linkIdSrc);
				org.jsoup.nodes.Document doc = Jsoup.parse(html);
				String title = doc.select("title").text();
				News news = new News();
				news.setTitle(title);
				news.setHtml(html);        				    // 拿得到的新闻具体内容
				news.setContent(replaceContent(html).replaceAll("&quot;", "").replaceAll("&#58;", ":").replaceAll("<h4 class=related_title><i class=fa fa-tags></i> 相关阅读</h4>", "").replaceAll("0 >", "").replaceAll("</i> 0", ""));      // 替换掉新闻中的标签
				news.setCategory(0);
				news.setHospital(999);
				news.setNewsId(Tools.getInt(linkIdSrc));
				news.setSummary(title); 			// 新闻标题
				String imgs = imgsCompare(doc, "");		// 把新闻里面的图片取出来
				news.setImg(imgs);
				Integer nid = (Integer)DBTools.db("basedb").addItem(news);
				map.put("link_id", nid);
				DBTools.db("basedb").modItem("visit_point_link", map);
			}	
		}
	}
%>
<%!
	public void setTimeDifference() {
		List<Map> list = QBuilder.db("basedb").queryHql("from visit_template where category=0");	
		for (Map map:list) {
			Integer templateId = (Integer)map.get("id");
			String srcId = (String)map.get("src_id");
			String json = showCase(srcId);
			map.put("json", json);
			DBTools.db("basedb").modItem("visit_template", map);
			Map tMap = JSONUtil.fromJson(json, new TypeReference<Map>(){});
			Map model = (Map)tMap.get("model");
			List<Map> templatePointList = (List<Map> )model.get("templatePointList");
			List<Integer> timeList = new ArrayList<>();
			for (Map tempPoint:templatePointList) {
				List<Map> pointLinkList = (List<Map>)tempPoint.get("pointLinkList");
				Map timeMap = pointLinkList.get(0);
				timeList.add(Tools.getInt((timeMap.get("timeDifference") + "").replace(".0", "")));
			}
			List<Map> points = QBuilder.db("basedb").queryHql("from visit_point where template_id=" + templateId);
			for (int i = 0;i<points.size();i++) {
				Map pointMap = points.get(i);
				pointMap.put("time_difference", timeList.get(i));
				DBTools.db("basedb").modItem("visit_point", pointMap);
			}
			//if (true) return;
		}
	}
	
	public void modNews() {
		List<News> list = QBuilder.db("basedb").select().from("News").where(new Where("hospital=", 999).and("category=", 0).and("status = ", STATUS_ENABLE)).query().getResultObj();
		for (News news:list) {
			String content = news.getContent();
			org.jsoup.nodes.Document doc = Jsoup.parse(content);
			doc.select("h2").next().remove();
			doc.select("h2").remove();  
			news.setContent(doc.toString().replaceAll("医数", "天下布医"));
		}
		DBTools.db("basedb").modItem(list);
	}
	
	public void modSurveyShowOrder() {
		List<Map> points = QBuilder.db("basedb").select().from("visit_point").where(new Where("status = ", STATUS_ENABLE)).query().getResultObj();
		List<Integer> idList = new ArrayList<>();
		for (Map point:points) {
			idList.add((Integer)point.get("template_id"));
		}
		for (Integer templateId:idList) {
			int i = 1;
			for (Map point:points) {
				Integer id = (Integer)point.get("template_id");
				if (id.equals(templateId)) {
					point.put("show_order", i);
					
					i++;
				}
			}
		}
		DBTools.db("basedb").modItem("visit_point", points);
	}
	
	public void modNewsBlank() {
		List<Map> pointLinks = QBuilder.db("basedb").queryHql("from visit_point_link where link_id is null");
		for (Map map:pointLinks) {
			Map jsonMap = JSONUtil.fromJson(map.get("json") + "", new TypeReference<Map>(){});
			String linkId = Tools.getDesc(jsonMap.get("linkId")).replace(".0", "");
			List<News>  nList = QBuilder.db("basedb").queryHql("from News where newsId='" + linkId + "' and hospital=999 and category=0");			
			if (nList.size() != 0) {
				News exS = nList.get(0);
				map.put("link_id", exS.getId());
			} else {
				String html = HttpUtil.get("https://ms.ifuifu.com/Index/detail/id/" + linkId);
				org.jsoup.nodes.Document doc = Jsoup.parse(html);
				String title = doc.select("title").text();
				News news = new News();
				news.setTitle(title);
				news.setHtml(html);        				    // 拿得到的新闻具体内容
				news.setContent(replaceContent(html).replaceAll("&quot;", "").replaceAll("&#58;", ":").replaceAll("<h4 class=related_title><i class=fa fa-tags></i> 相关阅读</h4>", "").replaceAll("0 >", "").replaceAll("</i> 0", ""));      // 替换掉新闻中的标签
				news.setCategory(0);
				news.setHospital(999);
				news.setNewsId(Tools.getInt(linkId));
				news.setSummary(title); 			// 新闻标题
				String imgs = imgsCompare(doc, "");		// 把新闻里面的图片取出来
				news.setImg(imgs);
				news.setAuthor("天下布医官方");
				news.setTime("2017-06-05");
				Integer nid = (Integer)DBTools.db("basedb").addItem(news);
				System.out.println(nid == null);
				map.put("link_id", nid);
			}
		}
		DBTools.db("basedb").modItem("visit_point_link", pointLinks);
		modNews();
	}
%>
<%
	//InitToken();
	//saveCategory();template();
	//detail();
	//setTimeDifference();
	
	//modSurveyShowOrder();
	//modNewsBlank();
%>